<template>
  <view class="container">
    <!-- 账户信息卡片 -->
    <view class="account-card">
      <view class="account-header">
        <text>账户余额</text>
        <text class="amount"
          >{{ store.state.user.supplierInfo.bill_amount }}元</text
        >
      </view>

      <view class="account-details">
        <view class="detail-item">
          <text>可提现金额</text>
          <text class="value"
            >{{ store.state.user.supplierInfo.bill_amount_withdrawn }}元</text
          >
        </view>
        <view class="detail-item">
          <text>冻结金额</text>
          <text class="value"
            >{{ store.state.user.supplierInfo.bill_amount_freeze }}元</text
          >
        </view>
      </view>
    </view>

    <!-- 提现按钮 -->
    <view class="withdraw-btn">
      <u-button type="primary" @click="showWithdrawModal = true"
        >申请提现</u-button
      >
    </view>

    <!-- 资金明细 -->
    <view class="section-title">
      <text>资金明细</text>
    </view>

    <view class="transaction-list">
      <view
        class="transaction-item"
        v-for="(item, index) in transactions"
        :key="index"
      >
        <view class="transaction-info">
          <text class="type">{{ item.type }}</text>
          <text class="date">{{ item.date }}</text>
        </view>
        <text class="amount" :class="item.amount > 0 ? 'income' : 'expense'">
          {{ item.amount > 0 ? "+" : "" }}{{ item.amount }}元
        </text>
      </view>
      <template v-if="transactions.length == 0">
        <u-empty></u-empty>
      </template>
    </view>

    <!-- 提现申请模态框 -->
    <up-modal
      :show="showWithdrawModal"
      title="申请提现"
      @cancel="showWithdrawModal = false"
    >
      <u-form
        :model="withdrawForm"
        :rules="withdrawRules"
        ref="withdrawFormRef"
        label-width="5em"
      >
        <u-form-item label="提现金额" prop="amount">
          <u-input
            v-model="withdrawForm.amount"
            placeholder="请输入提现金额"
            type="number"
          >
            <template #suffix>
              <text>元</text>
            </template>
          </u-input>
        </u-form-item>

        <u-form-item label="银行卡" prop="bank_id">
          <u-input v-model="bankLabel" readonly placeholder="选择银行卡">
            <template #suffix>
              <u-button type="primary" @click="handleToSelectBank" size="small"
                >选择</u-button
              >
            </template>
          </u-input>
        </u-form-item>
      </u-form>

      <template #confirmButton>
        <view class="flex gap-20">
          <u-button type="error" size="small" @click="showWithdrawModal = false"
            >取消</u-button
          >
          <u-button type="primary" size="small" @click="handleWithdrawSubmit">
            确认提现
          </u-button>
        </view>
      </template>
    </up-modal>

    <u-picker
      :show="pickerShow"
      :columns="bankList"
      keyName="bank_name"
      @confirm="handleBankConfirm"
    >
    </u-picker>
  </view>
</template>

<script setup>
import { ref } from "vue";
import { useStore } from "vuex";
import { onShow } from "@dcloudio/uni-app";
import {
  supplierWithdraw,
  supplierWithdrawRecord,
} from "@/common/apis/supplier.js";
import { getBankList } from "@/common/apis/user.js";

const store = useStore();

const pickerShow = ref(false);
const showWithdrawModal = ref(false);
const withdrawForm = ref({
  amount: "",
  bank_id: "",
});
const withdrawFormRef = ref(null);

const withdrawRules = ref({
  amount: [
    { required: true, message: "请输入提现金额", trigger: "blur" },
    {
      pattern: /^\d+(\.\d{1,2})?$/,
      message: "请输入正确金额格式",
      trigger: "blur",
    },
  ],
});

async function handleWithdrawSubmit() {
  try {
    console.log(withdrawForm.value);
    await withdrawFormRef.value.validate();
    if (
      withdrawForm.value.amount >
      store.state.user.supplierInfo.bill_amount_withdrawn
    ) {
      return uni.showToast({
        title: "提现金额不能大于可提现金额",
        icon: "none",
      });
    }
    if (!withdrawForm.value.bank_id) {
      return uni.showToast({
        title: "请选择银行卡",
        icon: "none",
      });
    }
    const response = await supplierWithdraw(withdrawForm.value);

    uni.showToast({
      title: "提现申请已提交",
      icon: "success",
    });

    showWithdrawModal.value = false;
    // 刷新数据
    fetchWithdrawRecord();
  } catch (error) {
    console.error("提现申请失败:", error);
    uni.showToast({
      title: error.message || "提现申请失败",
      icon: "none",
    });
  }
}

// 模拟交易记录
const transactions = ref([]);

// 提现操作
const handleWithdraw = () => {
  uni.navigateTo({
    url: "/pages/supplier/withdraw-apply",
  });
};

async function fetchWithdrawRecord() {
  const response = await supplierWithdrawRecord();
  transactions.value = response.records; // 假设返回的是一个数组
}

const bankList = ref([[]]);

function handleToSelectBank() {
  if (bankList.value[0].length == 0) {
    return uni.showModal({
      title: "提示",
      content: "请先添加银行卡",
      showCancel: true,
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({
            url: "/pages/user/bank/add",
          });
        }
      },
    });
  } else {
    pickerShow.value = true;
  }
}

async function initBankList() {
  const response = await getBankList();
  if (response) {
    bankList.value = [response];
  }
}

const bankLabel = ref("");

function handleBankConfirm(event) {
  const { value } = event;
  withdrawForm.value.bank_id = value[0].id;
  bankLabel.value = value[0].bank_name;
  pickerShow.value = false;
}

// 页面显示时加载数据
onShow(() => {
  fetchWithdrawRecord();
  initBankList();
  // 这里可以添加加载数据的逻辑
});
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
}

.account-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .account-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .amount {
      font-size: 36rpx;
      font-weight: bold;
      color: #ff2b2b;
    }
  }

  .account-details {
    display: flex;
    justify-content: space-between;

    .detail-item {
      flex: 1;
      text-align: center;

      .value {
        display: block;
        margin-top: 10rpx;
        font-size: 28rpx;
        color: #666;
      }
    }
  }
}

.withdraw-btn {
  margin: 30rpx 0;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin: 20rpx 0;
}

.transaction-list {
  background: #fff;
  border-radius: 16rpx;
  padding: 0 30rpx;

  .transaction-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }

    .transaction-info {
      flex: 1;

      .type {
        display: block;
        font-size: 30rpx;
        margin-bottom: 10rpx;
      }

      .date {
        font-size: 24rpx;
        color: #999;
      }
    }

    .amount {
      font-size: 32rpx;
      font-weight: bold;

      &.income {
        color: #09bb07;
      }

      &.expense {
        color: #ff2b2b;
      }
    }
  }
}
</style>
